﻿using CefSharp;
using CefSharp.Handler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PidKeyReptile.Desktop.Helper
{
    public class CheckerRequestHandler: RequestHandler
    {
        protected override bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect)
        {
            return base.OnBeforeBrowse(chromiumWebBrowser, browser, frame, request, userGesture, isRedirect);   
        }

        protected override bool OnOpenUrlFromTab(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture)
        {
            return base.OnOpenUrlFromTab(chromiumWebBrowser, browser, frame, targetUrl, targetDisposition, userGesture);
        }

        protected override IResourceRequestHandler GetResourceRequestHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling)
        {
            if (request.Url.EndsWith("pidms_main.js"))
            {
               return new CustomRequestHandler();
            }

            return base.GetResourceRequestHandler(chromiumWebBrowser, browser, frame, request, isNavigation, isDownload, requestInitiator, ref disableDefaultHandling);
        }

        protected override void OnDocumentAvailableInMainFrame(IWebBrowser chromiumWebBrowser, IBrowser browser)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("(function(){")
                .Append("CefSharp.BindObjectAsync('boundAsync');")
                .Append("document.getElementsByTagName('head')[0].appendChild(document.createElement('script')).src = 'http://127.0.0.1:8848/PidKeyJsDecryption/js/expand_call.js'")
                .Append("})();");
            chromiumWebBrowser.GetMainFrame().EvaluateScriptAsync(sb.ToString());

            base.OnDocumentAvailableInMainFrame(chromiumWebBrowser, browser);
        }

        protected override void OnRenderViewReady(IWebBrowser chromiumWebBrowser, IBrowser browser)
        {

            base.OnRenderViewReady(chromiumWebBrowser, browser);
        }
    }
}
